package org.leiyang.common.coder;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.leiyang.common.dtos.Message;
import org.leiyang.common.util.Constants;
import org.leiyang.common.util.ProtostuffUtils;

public class MsgEncoder extends MessageToByteEncoder {

    @Override
    public void encode(ChannelHandlerContext ctx, Object in, ByteBuf out) {
        if (in instanceof Message) {
            byte[] bytes = ProtostuffUtils.serialize(in);
            byte[] delimiter = Constants.DELIMITER.getBytes();
            //粘包
            byte[] total = new byte[bytes.length + delimiter.length];
            System.arraycopy(bytes, 0, total, 0, bytes.length);
            System.arraycopy(delimiter, 0, total, bytes.length, delimiter.length);

            out.writeBytes(total);
        }
    }
}
